import React, { memo, Fragment, useState, useEffect, useCallback } from "react";
import { withRouter } from "react-router-dom";
import { message } from "antd";
import Qs from "qs";

import { departAdd, departDetailed } from "services/common";

import HYFormCom from "components/form/index";
// 配置信息
const formItem = [
  {
    type: "Input",
    label: "部门名称",
    name: "name",
    required: true,
    style: { width: "200px" },
    placeholder: "请输入部门名称",
  },
  {
    type: "InputNumber",
    label: "人员数量",
    name: "number",
    required: true,
    min: 1,
    max: 100,
    style: { width: "200px" },
    placeholder: "请输入人员数量",
  },
  {
    type: "Radio",
    label: "禁启用",
    name: "status",
    required: true,
    options: [
      { label: "禁用", value: false },
      { label: "启用", value: true },
    ],
  },
  {
    type: "TextArea",
    label: "描述",
    name: "content",
    required: true,
    placeholder: "请输入描述内容",
  },
];
const formLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};
const initialValues = {
  status: false,
};

const HYdDepartmentAdd = memo(function (props: any) {
  // 状态
  const [isEdit, setIsEdit] = useState(false);
  const [id, setId] = useState<string>();
  const [editData, setEditData] = useState({});
  // 生命周期
  const handleParams = useCallback(async () => {
    const search = props.location.search;
    if (search) {
      const id = Qs.parse(search)["?id"];
      const ids = id as string;
      if (!!ids) {
        setIsEdit(true);
        setId(ids);
        edit(ids);
      }
    }
  }, [props.location.search]);
  useEffect(() => {
    handleParams();
  }, [handleParams]);

  const edit = async (id: string) => {
    const res: any = await departDetailed({ id });
    setEditData({ ...res.data });
  };
  //
  const onFinish = async (params: any, form: any) => {
    try {
      //  添加 修改
      if (id) {
        params.id = +id;
      }
      const res: any = await departAdd(params);
      message.success(res.message);
      form.resetFields();
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <Fragment>
      <HYFormCom
        formItem={formItem}
        formLayout={formLayout}
        submit={onFinish}
        editData={editData}
        initialValues={initialValues}
        isEdit={isEdit}
      />
    </Fragment>
  );
});

export default withRouter(HYdDepartmentAdd);
